package com.iot.gateway.tsl.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.iot.gateway.tsl.mapper.TslProductMapper;
import com.iot.gateway.tsl.model.TslProductEntity;
import com.iot.gateway.tsl.qo.ProductQo;
import com.iot.gateway.tsl.service.TslProductService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class TslProductServiceImpl implements TslProductService {

    private final TslProductMapper productMapper;

    public TslProductServiceImpl(TslProductMapper productMapper) {
        this.productMapper = productMapper;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addProduct(ProductQo product) {
        TslProductEntity entity = new TslProductEntity();
        BeanUtils.copyProperties(product, entity);
        productMapper.insert(entity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateProduct(ProductQo product) {
        // 仅更新 version
        LambdaUpdateWrapper<TslProductEntity> uw = new LambdaUpdateWrapper<TslProductEntity>()
                .eq(TslProductEntity::getProductKey, product.getProductKey())
                .set(TslProductEntity::getVersion, product.getVersion());
        productMapper.update(null, uw);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteProduct(String productKey) {
        productMapper.deleteById(productKey);
    }

    @Override
    public ProductQo getProduct(String productKey) {
        TslProductEntity entity = productMapper.selectById(productKey);
        if (entity == null) {
            return null;
        }
        ProductQo qo = new ProductQo();
        BeanUtils.copyProperties(entity, qo);
        return qo;
    }

    @Override
    public List<ProductQo> listProducts() {
        return productMapper.selectList(null)
                .stream()
                .map(e -> {
                    ProductQo qo = new ProductQo();
                    BeanUtils.copyProperties(e, qo);
                    return qo;
                })
                .collect(Collectors.toList());
    }
}
